package com.outstanding.his.medicine.dao.impl;

import java.util.Collection;

import org.hibernate.Query;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.outstanding.his.medicine.dao.IMedicineDao;
import com.outstanding.his.medicine.domain.Medicine;
import com.outstanding.his.medicine.service.impl.MedicineService;

public class HibernateMedicineDao extends HibernateDaoSupport implements
		IMedicineDao {

	@Override
	@Transactional
	public Medicine submitMedicine(Medicine medicine)
			throws DataAccessException {
		this.getHibernateTemplate().saveOrUpdate(medicine);
		return medicine;
	}

	@Override
	public Medicine getMedicine(Integer medicineId) throws DataAccessException {
		Medicine medicine = (Medicine) this.getSession().load(Medicine.class,
				medicineId);
		return medicine;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Medicine> getMedicineList() throws DataAccessException {
		Collection<Medicine> medicines = this.getSession().createQuery(
				"from Medicine").list();
		return medicines;
	}

	@Override
	public Medicine updateMedicine(Medicine medicine)
			throws DataAccessException {
		this.getHibernateTemplate().update(medicine);
		return medicine;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Medicine> getWesternMedicineList()
			throws DataAccessException {
		String sql = "from Medicine where medicineCategory =:medicineCategory";

		Query query = this.getSession().createQuery(sql);
		query
				.setParameter("medicineCategory",
						MedicineService.WESTERN_MEDICINE);

		Collection<Medicine> medicines = query.list();
		
		return medicines;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Medicine> getChineseMedicineList()
			throws DataAccessException {
		Collection<Medicine> medicines = this.getSession().createQuery(
				"from Medicine where medicineCategory ="
						+ MedicineService.CHINESE_MEDICINE).list();
		return medicines;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Medicine> getInsulinMedicineList()
			throws DataAccessException {
		Collection<Medicine> medicines = this.getSession().createQuery(
				"from Medicine where medicineCategory ="
						+ MedicineService.INSULIN_MEDICINE).list();
		return medicines;
	}

}
